import { gkhCreate } from './tools';

function RightMenu(parentNode) {
  const node = gkhCreate('ul', {
    className: 'gkh_right_menu',
    target: parentNode,
  });
  this.items = {};

  function rightClick(event) {
    const e = event || window.event;
    const { offsetHeight, offsetWidth } = document.body;
    const { offsetHeight: nodeHeight, offsetWidth: nodeWidth } = node;
    const { top, left } = parentNode.getBoundingClientRect();
    const clientX = e.clientX - left;
    const clientY = e.clientY - top;
    let x = clientX - 5;
    let y = clientY - 5;
    if (clientX + nodeWidth > offsetWidth) {
      x = clientX - nodeWidth + 5;
    }
    if (clientY + nodeHeight > offsetHeight) {
      y = clientY - nodeHeight + 5;
    }
    node.style.left = x.toString().concat('px');
    node.style.top = y.toString().concat('px');
    node.style.visibility = 'visible';
    return false;
  }
  // 禁止右键默认事件
  parentNode.oncontextmenu = rightClick;

  node.onmouseleave = function () {
    node.style.visibility = 'hidden';
  };

  this.addItem = (props) => {
    if (props instanceof Array) {
      const li = gkhCreate('li', {
        target: node,
      });
      props.forEach(({ text, click, id }) => {
        if (id) {
          const itemNode = gkhCreate('div', {
            target: li,
            innerText: text,
          });
          itemNode.gukh_disabled_value = false;
          itemNode.butId = id;
          itemNode.disabled1 = false;
          itemNode.onclick = function () {
            node.style.visibility = 'hidden';
            click();
          };
          Object.defineProperties(itemNode, {
            disabled: {
              configurable: false, // 设置属性可以更改，默认为false
              set: function (value) {
                itemNode.gukh_disabled_value = value;
                let className = itemNode.getAttribute('class');
                if (className) {
                  className = className.replace(' disabled', ' ');
                } else {
                  className = '';
                }
                if (value) {
                  className = className.concat(' disabled');
                }
                itemNode.setAttribute('class', className);
              },
              get: function () {
                return itemNode.gukh_disabled_value;
              },
            },
          });
          this.items[id] = itemNode;
        }
      });
    }
  };

  this.clearItems = () => {
    node.innerHTML = '';
    this.items = {};
  };

  this.destruction = () => {
    parentNode.removeChild(node);
  };
  return this;
}

function createRightMenu(node) {
  return new RightMenu(node);
}

export { createRightMenu };
